﻿using System;
using System.Net;
using System.Text;
using java = biz.ritter.javapi;
using biz.ritter.javapi.io;
using biz.ritter.javapi.dotnet.util.wrapper;

namespace biz.ritter.javapi.net
{
    /// <summary>
    /// 
    /// </summary>
    [Serializable]
    public class URLConnection
    {
        /// <summary>
        /// <i>Hence every HttpWebRequest is a HttpWebRequest,
        /// </summary>
        private HttpWebRequest delegateInstance;

        internal URLConnection(HttpWebRequest wr)
        {
            this.delegateInstance = wr;
        }

        /// <summary>
        /// Read from stream i and write to stream o.
        /// </summary>
        /// <param name="inStream">input stream</param>
        /// <param name="outStream">output stream</param>
        /// <returns>count of byte transferred</returns>
        private static int Pipe(System.IO.Stream inStream, System.IO.Stream outStream)
        {
            const int bufferLength = 4096;
            byte[] buf = new byte[bufferLength];

            int read = 0;
            int length = 0;

            while ((read = inStream.Read(buf, 0, bufferLength)) > 0)
            {
                outStream.Write(buf, 0, read);
                length += read;
            }
            return length;
        }

        private static byte[] ReadAll(System.IO.Stream s)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                Pipe(s, ms);
                ms.Close();
                return ms.ToArray();
            }
        }

        /// <summary>
        /// getInputStream
        /// </summary>
        /// <returns></returns>
        public InputStream getInputStream()
        {
            WebResponse response = this.delegateInstance.GetResponse();
            return new InputStreamWrapper(response.GetResponseStream());
        }
    }
}
